'''
Created on May 30, 2011

@author: Karl
'''
from twitter.api import Twitter, TwitterError
from twitter.oauth import OAuth, read_token_file
from optparse import OptionParser
import os
import time
import json
import urllib2

CONSUMER_KEY='uS6hO2sV6tDKIOeVjhnFnQ'
CONSUMER_SECRET='MEYTOS97VvlHX7K1rwHPEqVpTSqZ71HtvoK4sVuYk'

TEST_MODE = False

DEFAULT_USERNAME = 'tweetmyscores' 

DEFAULT_AUTH_FILENAME = '.twitter_oauth'
DEFAULT_LASTID_FILENAME = '.twitter_lastid'
Response_File = 'Response.txt'
public_Status_update_File = 'Status_update.txt'
questions_status_update_File = 'question_status.txt'
make_Friends_File = 'friends.txt'
count = 33 
response_count = 0 
question_count = 32
lastid = ''

def status_update(outgoing_text):  
    if not TEST_MODE:
        print '====> Resp =', outgoing_text
        try:
            poster.statuses.update(status=outgoing_text)
        except TwitterError as e:
            print '*** Twitter returned an error:\n***%s' % e
            
    else:
        print '====> (TEST MODE) Resp =', outgoing_text
        
#ACHV: Followers, Tweets
def achievements(user):
    following = urllib2.urlopen('http://api.twitter.com/1/users/show.json?screen_name=' + user)
    friend_str = following.read()
    friend_obj = json.loads(friend_str)
    achv = ''
    statuse = friend_obj['statuses_count']
    follower = friend_obj['followers_count']
    if follower >= 1000:
        achv = 'ACHV: 1000+ Followers'
    elif follower >= 500:
        achv = 'ACHV: 500+ Followers'
    elif follower >= 100:
        achv = 'ACHV: 100+ Followers'
    if statuse >= 2000:
        achv = achv + ', 2000+ Tweets'
    elif statuse >= 1000:
        achv = achv + ', 1000+ Tweets'
    elif statuse >= 500:
        achv = achv + ', 500+ Tweets'
    return achv

def  calculate_score(user):
    following = urllib2.urlopen('http://api.twitter.com/1/users/show.json?screen_name=' + user)
    friend_str = following.read()
    friend_obj = json.loads(friend_str)
    score = ((friend_obj['followers_count']*.03) + (friend_obj['statuses_count']*.01) + 
            (friend_obj['listed_count']*.04) + (friend_obj['friends_count']*.01))
    if score > 100:
        score = 100
    return score
     
def reply_to_tweets():
    global lastid
    results = reader.search(q=username, since_id=lastid)['results']
    
    if not results:
        print 'No results this time...'

        # process results in reverse order (i.e., chronological order)
    for result in reversed(results):
        asker = result['from_user']
        msgid = str(result['id'])
        incoming_text = result['text']
        print " <<< " + asker + ": " + incoming_text
        if incoming_text.lower().find(username) != 0:
            print '====> No response (not directed to %s)' % (username,)
        elif (lastid != '') and (long(msgid) <= long(lastid)):
            print '====> No response (%s < %s)' % (msgid, lastid)
        else:
            try:
                score = str(calculate_score(asker))
                achieve =  achievements(asker)
            except urllib2.HTTPError as e:
                print '*** Twitter returned an error:\n***%s' % e
            text = 'Your lifetime twitter score is ' + score + ' of 100.'
            outgoing_text = '@%s %s %s ' % (str(asker), text, achieve)
            print '====> Resp = %s' % outgoing_text
            try:
                status_update(outgoing_text)
            except TwitterError as e:
                print '*** Twitter returned an error:\n***%s' % e
            else:
                lastid = msgid
                print 'Last id replied = ', lastid
                with open(lastid_filename, 'w') as f:
                    f.write(lastid)
    print 'Now sleeping... \n\n'
    time.sleep(5)
                    
if __name__ == '__main__':

    parser = OptionParser()
    parser.add_option('-u', '--username', dest='username')
    parser.add_option('-o', '--oauthfile', dest='oauthfile')
    parser.add_option('-l', '--lastid', dest='lastid')
    (options, args) = parser.parse_args()
    
    home_dir = os.environ.get('HOME', '')
    
    if options.username:
        username = options.username
    else:
        username = DEFAULT_USERNAME

    if username[0] != '@':
        username = '@' + username
    
    if options.oauthfile:
        oauth_filename = options.oauthfile
    else:
        oauth_filename = home_dir + os.sep + DEFAULT_AUTH_FILENAME
    oauth_token, oauth_token_secret = read_token_file(oauth_filename)
    
    if options.lastid:
        lastid = options.lastid
    else:
        lastid_filename = home_dir + os.sep + DEFAULT_LASTID_FILENAME
        try:
            with open(lastid_filename, 'r') as f:
                lastid = f.readline()
        except IOError:
            lastid = ''
            
    reader = Twitter(domain='search.twitter.com')
    reader.uriparts=()
    
    poster = Twitter(
        auth=OAuth(
            oauth_token, oauth_token_secret, CONSUMER_KEY, CONSUMER_SECRET),
        secure=True,
        api_version='1',
        domain='api.twitter.com')
    while True:
        reply_to_tweets()